﻿using System;
using System.Windows.Forms;
using IchiaTester.Utils;

namespace IchiaTester
{
    public partial class LoginForm : Form
    {
        private MainForm mainForm;

        public LoginForm(MainForm form)
        {
            mainForm = form;
            InitializeComponent();

            this.lbAppName.Text = SystemSetting.SOFTWARE_NAME;
            this.lbAppVer.Text = SystemSetting.SOFTWARE_VERSION;
            this.lbReleaseDate.Text = SystemSetting.RELEASE_DATE;

            gb1.Paint += new GroupBoxPaint().groupbox_Paint;
            gb2.Paint += new GroupBoxPaint().groupbox_Paint;
        }

        private void LoginForm_Load(object sender, EventArgs e)
        {
            tbUserName.Focus();
        }

        /// <summary>
        /// 校验登录的用户名和hash加密后的密码
        /// </summary>
        /// <param name="inputUserName">输入的用户名</param>
        /// <param name="inputPassword">输入的密码</param>
        /// <returns></returns>
        private bool VerifyInput(string inputUserName, string inputPassword)
        {
            //Check if user exist in list
            if (SystemSetting.UserInfoDict.TryGetValue(inputUserName, out UserInfo userData))
            {
                //Check if password is correct
                if (inputPassword == userData.HashPassword)
                {
                    SystemSetting.isAdmin = userData.Permission == "Admin" ? true : false;
                    SystemSetting.isEngineer = userData.Permission == "Engineer" ? true : false;
                    return true;
                }

                return false;
            }

            return false;
        }

        /// <summary>
        /// 登入按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnLogin_Click(object sender, EventArgs e)
        {
            if (tbUserName.Text == "" || tbPassword.Text == "")
            {
                MessageBox.Show("欄位不能空白", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                //super user
                if (tbUserName.Text == SystemSetting.SUPER_USER && tbPassword.Text == SystemSetting.SUPER_USER_PW)
                {
                    //if login correct turn on system config and user config
                    mainForm.menuEngineerMode.Enabled = true;
                    mainForm.menuSystemConfig.Enabled = true;
                    mainForm.menuUserConfig.Enabled = true;
                    mainForm.menuSerialPortConfig.Enabled = true;
                    mainForm.menuUserLogin.Enabled = false;
                    mainForm.menuUserLogout.Enabled = true;

                    mainForm.groupBoxStartButton.Enabled = true;
                    mainForm.groupBoxResultDisplay.Enabled = true;
                    if (DataManager.IsPortAvailable)
                    {
                        mainForm.tbResult.Text = System_msg.WAIT_STR;
                    }
                    else
                    {
                        mainForm.tbResult.Text = System_msg.CHECK_SERIAL_PORT;
                    }

                    SystemSetting.isAdmin = true;
                    SystemSetting.isEngineer = false;
                    SystemSetting.loginUserName = "Admin";
                    mainForm.DisplayWorkerInfo();
                    this.DialogResult = DialogResult.OK;
                }
                else
                {
                    //search user in list
                    if (SystemSetting.UserInfoDict.Count <= 0)
                    {
                        // 使用者设定的用户为空
                        MessageBox.Show("登入失敗，使用者設定檔內容為空", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    else
                    {
                        //Convert input to hash password 将输入的密码转化为hash加密后的内容
                        string inputHashPassword = DataSecureHelper.GetHash(tbPassword.Text);

                        // 校验登录的用户名和hash加密后的密码
                        if (VerifyInput(tbUserName.Text, inputHashPassword))
                        {
                            // 密码错误,登录失败
                            MessageBox.Show("登入失敗", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        else
                        {
                            // 密码正确,登录成功;判断用户属于什么角色
                            if (SystemSetting.isAdmin)
                            {
                                //Admin 超级管理员
                                mainForm.menuEngineerMode.Enabled = true;
                                mainForm.menuSystemConfig.Enabled = true;
                                mainForm.menuUserConfig.Enabled = true;
                                mainForm.menuSerialPortConfig.Enabled = true;
                                mainForm.groupBoxStartButton.Enabled = true;
                                mainForm.groupBoxResultDisplay.Enabled = true;
                            }
                            else if (SystemSetting.isEngineer)
                            {
                                //Engineer 工程师
                                mainForm.menuEngineerMode.Enabled = false;
                                mainForm.menuSystemConfig.Enabled = true;
                                mainForm.menuUserConfig.Enabled = true;
                                mainForm.menuSerialPortConfig.Enabled = true;
                                mainForm.groupBoxStartButton.Enabled = true;
                                mainForm.groupBoxResultDisplay.Enabled = true;
                            }
                            else
                            {
                                //User 普通用户
                                mainForm.menuEngineerMode.Enabled = false;
                                mainForm.menuSystemConfig.Enabled = false;
                                mainForm.menuUserConfig.Enabled = false;
                                mainForm.menuSerialPortConfig.Enabled = false;
                                mainForm.groupBoxStartButton.Enabled = true;
                                mainForm.groupBoxResultDisplay.Enabled = false;
                            }

                            mainForm.menuUserLogin.Enabled = false;
                            mainForm.menuUserLogout.Enabled = true;
                            SystemSetting.loginUserName = tbUserName.Text;
                            mainForm.DisplayWorkerInfo();
                            
                            // 检查串口是否可用
                            if (DataManager.IsPortAvailable)
                            {
                                mainForm.tbResult.Text = System_msg.WAIT_STR;
                            }
                            else
                            {
                                mainForm.tbResult.Text = System_msg.CHECK_SERIAL_PORT;
                            }

                            this.DialogResult = DialogResult.OK;
                            return;
                        }
                    }
                }
            }
        }

        private void tbUserName_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                tbPassword.Focus();
            }
        }

        private void tbPassword_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnLogin.Focus();
            }
        }
    }
}